package com.hwadee.backend.controller;

import com.hwadee.backend.entity.Result;
import com.hwadee.backend.entity.user.User;
import com.hwadee.backend.service.AuthorizeService;
import com.hwadee.backend.service.UserService;
import com.hwadee.backend.service.HealthRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hwadee.backend.entity.HealthRecord.HealthRecord;
import com.hwadee.backend.util.HealthRecordConverter;

@RestController
@RequestMapping("/api/patients")
public class PatientController {

    private final AuthorizeService authorizeService;
    private final UserService userService;
    private final HealthRecordService healthRecordService;
    private static final Logger logger = LoggerFactory.getLogger(PatientController.class);

    @Autowired
    public PatientController(AuthorizeService authorizeService, UserService userService, HealthRecordService healthRecordService) {
        this.authorizeService = authorizeService;
        this.userService = userService;
        this.healthRecordService = healthRecordService;
    }

    @PostMapping("/{response}/request-auth")
    public Result requestAuthorization(@PathVariable int response, @RequestBody Map<String, String> request) {
        String applicantUsername = request.get("applicant");
        Result userResult = userService.getUserByUsername(applicantUsername);
        if (!userResult.isSuccess()) {
            return Result.error("申请人不存在");
        }
        User user = (User) userResult.getData();
        int result = authorizeService.createAuthorizationRequest(user.getId(), response);
        return result > 0 ? Result.success("授权请求已发送") : Result.error("授权请求失败");
    }

    @PutMapping("/{response}/authorization-response")
    public Result updateAuthorizationResponse(@PathVariable int response, @RequestBody Map<String, Object> request) {
        int applicant = (int) request.get("applicant");
        String status = (String) request.get("status");
        int result = authorizeService.updateAuthorizationResponse(applicant, response, status);
        return result > 0 ? Result.success("授权状态已更新") : Result.error("更新授权状态失败");
    }

    @GetMapping("/authorization-status/{response}")
    public Result getAuthorizationStatus(@PathVariable int response, @RequestParam int applicant) {
        String status = authorizeService.getAuthorizationStatus(applicant, response);
        return Result.success(status);
    }

    /**
     * 根据患者ID查询所有记录
     */
    @GetMapping("/{patientId}/records")
    public Result getPatientRecords(@PathVariable Integer patientId) {
        Map<String, List<?>> records = new HashMap<>();
        records.put("allergyHistory", healthRecordService.getAllergyHistory(patientId));
        records.put("familyHistory", healthRecordService.getFamilyHistory(patientId));
        records.put("healthIndicators", healthRecordService.getHealthIndicators(patientId));
        records.put("medicalExamReport", healthRecordService.getMedicalExamReport(patientId));
        records.put("medicationRecord", healthRecordService.getMedicationRecord(patientId));
        records.put("pastMedicalHistory", healthRecordService.getPastMedicalHistory(patientId));
        return Result.success(records);
    }

    /**
     * 更新患者记录
     */
    @PutMapping("/records/{id}")
    public Result updateRecord(@PathVariable Integer id, @RequestBody HealthRecord healthRecord) {
        try {
            logger.info("接收到更新请求: id={}, healthRecord={}", id, healthRecord);
            healthRecord.setRecordId(id);
            System.out.println("rasa"+healthRecord);
            int result = healthRecordService.updateHealthRecord(healthRecord);
            return result > 0 ? Result.success("记录更新成功") : Result.error("记录更新失败或未找到记录");
        } catch (Exception e) {
            logger.error("更新记录失败", e);
            return Result.error("更新记录失败：" + e.getMessage());
        }
    }

    /**
     * 删除患者记录
     */
    @DeleteMapping("/records/{recordId}")
    public Result deleteRecord(@PathVariable int recordId) {
        logger.info("删除健康记录，记录 ID: {}", recordId);
        try {
            authorizeService.removeRecordPermissions(recordId);
            int result = healthRecordService.deleteHealthRecord(recordId);
            if (result > 0) {
                // 删除成功后，移除相关权限
                return Result.success("记录删除成功");
            } else {
                return Result.error("记录删除失败或未找到记录");
            }
        } catch (Exception e) {
            logger.error("删除健康记录失败，记录 ID: {}", recordId, e);
            return Result.error( "删除健康记录失败");
        }
    }
    /**
     * 根据患者ID查询授权记录
     */
    @GetMapping("/{patientId}/authorizations")
    public Result getAuthorizationsByPatientId(@PathVariable Integer patientId) {
        logger.info("查询患者授权记录，患者ID: {}", patientId);
        try {
            List<Map<String, Object>> authorizations = authorizeService.getAuthorizationsByUserId(patientId);
            return Result.success(authorizations);
        } catch (Exception e) {
            logger.error("查询患者授权记录失败222，患者ID: {}", patientId, e);
            return Result.error("查询授权记录失败：" + e.getMessage());
        }
    }
}